package com.heima.search.listener;

import com.alibaba.fastjson.JSON;
import com.heima.common.contants.ArticleConstants;
import com.heima.model.search.vos.SearchArticleVo;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
public class SyncArticleESIndexListener {
    @Autowired
    private RestHighLevelClient client;

    @KafkaListener(topics = ArticleConstants.ARTICLE_ES_SYNC_TOPIC)
    public void onMessage(String message) {
        log.info("SyncArticleESIndexListener,message={}", message);

        // 反序列化
        SearchArticleVo searchArticleVo = JSON.parseObject(message, SearchArticleVo.class);

        // 1.创建request
        IndexRequest indexRequest = new IndexRequest("app_info_article")
                .id(searchArticleVo.getId().toString())
                .source(message, XContentType.JSON);

        try {
            client.index(indexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("SyncArticleESIndexListener-文章es索引同步失败");
        }
    }
}
